<template>
  <div class="map-view">
    <div class="header-view">提示:点击地块选中地块，再次点击地块取消选中</div>
      <MapView ref="landMap" 
        @init="initMap" 
        @onClick="onClickLand" 
        :queryString="getCookie('plantingPlanId')?` and plantingplanid=${getCookie('plantingPlanId')}`:''"
        @getLandList="getLandList"
        :location="locationObj"  />
      <div class="choose-view">
        <div style="background-color: #00000080;">待选</div>
        <div>已选</div>
        <div v-if="getCookie('plantingPlanTaskId')" style="background-color: #ff9c00;color: #fff;border:1px solid #ff9c00;">已估产</div>
      </div>
    <div class="location-view" @click="btnLocation">
      <Icon name="aim" class="icon-location"  color="#07c160" />
    </div>
    <div class="right-bottom-view">
         <Button plain
            type="success" 
            :key="item.value"
            v-for="item in btnList" 
            @click="btnOpen(item)" 
            class="btn-top">
            {{formdata[item.key]?getTextName(formdata[item.key],item.key):item.text}}
          </Button>
    </div>
    <Popup v-model:show="showPicker"  :position="popType==1?'top':'bottom'">
        <SearchPanel v-if="popType==1" @onClick="onSearch" @onCancel="showPicker=false" />
        <Picker v-else
          v-model="selectedValues"
          :columns="columns"
          :title="title" 
          :columns-field-names="{text:'meaning',value:'code'}"
          @cancel="showPicker = false"
          @confirm="onConfirm"
        />
    </Popup>
      <div class="footer-view">
       <div>
        已选<span>{{selectLandList.length}}</span>地块，共计<span>{{getMapSize}}</span>亩
       </div>
       <Button   v-if="queryType==1" type="success" class="btn-save" @click="btnSave"> 
          保 存
        </Button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive,computed } from 'vue';
import {
  getCommonSelect,
  getLandTypeList,
  getLandTagsList,
  getTimesLands,
  getProcessedLandList
} from '@/api/gis'
import MapView from '@/components/Map/index.vue'
import SearchPanel from './components/SearchPanel.vue'
import { getCookie,setCookie } from '@/utils/httpParamsHandler';
import { Button,Popup,Picker,Icon} from 'vant';
const showPicker:any = ref(false)
const title:any = ref('')
const formdata:any =reactive({})
const formdataKey:any =ref('')
const popType:any = ref(1)
const landMap:any =ref(null)
const btnList:any =ref([
  {text:'搜索位置',value:1,key:'key1',icon:'location-o'},
  {text:'地块分组',value:2,key:'landGroupId',icon:'envelop-o'},
  {text:'作物品种',value:3,key:'cropId',icon:'flower-o'},
  {text:'地块类型',value:4,key:'landTypeId',icon:'star-o'},
  {text:'地块标签',value:5,key:'landTagId',icon:'flag-o'}
]) 
const landGroupList:any =ref([])
const cropList:any =ref([])
const landTypeList:any =ref([])
const tagsTypeList:any =ref([])
const columns:any = ref([])
const selectedValues:any = ref([])
const selectLandList:any = ref([])
const guchangLandList:any = ref([])
const landMapList:any = ref([])
const locationObj = ref({})
let mapView:any= null
//0 查看详情 1 可以选择地块
const queryType:any = ref(0) 

onMounted(async ()=>{
  queryType.value =getCookie('query')||0
  if(getCookie('title')){
    document.title=decodeURIComponent(decodeURIComponent(getCookie('title')))||'--'
  }
  getSelectList()
  if(getCookie('plantingPlanId')){
    btnList.value = btnList.value.filter((item:any)=>item.value!=3)
  }
  window.setTimeout(() => {
    setCookie('title','')
    setCookie('plantingPlanId')
  }, 5000);
})

const getSelectList =async()=>{
  //分组
  let res:any = await getCommonSelect({page:1,limit:100,param1:getCookie('farmId'),lovCode:'TANC_LAND_GROUP'})
  if(res.success){
    landGroupList.value = res.data||[]
  }

 //作物
 let res1:any = await getCommonSelect({page:1,limit:100,param1:getCookie('farmId'),lovCode:'TANC_PLANTING_PLAN'})
  if(res1.success){
    cropList.value = res1.data||[]
  }

  //类型
  let res2:any = await getLandTypeList({page:1,limit:100,companyId:getCookie('companyId')})
  if(res2.success){
    landTypeList.value = res2.data.map((item:any)=>{
      return {
        meaning:item.landTypeName,
        code:item.landTypeId
      }
    })
  }

  //标签
  let res3:any = await getLandTagsList({page:1,limit:100,companyId:getCookie('companyId')})
  if(res3.success){
    tagsTypeList.value = res3.data.map((item:any)=>{
      return {
        meaning:item.tagName,
        code:item.landTagId
      }
    })
  }
}

const initMap =(view:any)=>{
  mapView=view
  landMap.value.getFarmLandList({})
}
const getLandList =async(data:any)=>{
  landMapList.value = data?.features
   console.log(data?.features,'========')
  //message: "0,150706,150707,150927,150926,150718,150717,150713,150712,150711,150709,150710"
    //处理农事 只能处理 该方案下固定的地块
    if(getCookie('plantingPlanId')){
          setSelectPlantList()
      }else{
         defaultSelectLandColors()
    }
}

 const getArraytList =(array:any, num:number)=> {
    const result = [];
    const cnt = array.length % num == 0 ? array.length / num : (Math.floor(array.length / num) + 1);
    for (let i = 0; i < cnt; i++) {
        let item = []
        for (let j = 0; j < num; j++) {
            let index = i * num + j;
            if (index < array.length) {
                if (i % 2 == 0) {
                    item.push(array[index])
                } else {
                    item.unshift(array[index])
                }
            }
        }
        result.push(item)
}
return result;
}

 const flattenArrayList =(arr:any)=> {
  return arr.reduce((acc:any, val:any) => Array.isArray(val) ? acc.concat(flattenArrayList(val)) : acc.concat(val), []);
}

const defaultSelectLandColors =async()=>{
       //选中地块默认选中改变颜色
       if(getCookie('timesId')!='1'&& getCookie('timesId')!='0'){
            let res:any = await getTimesLands({key:getCookie('timesId')})
              if(res.success){
                  selectLandList.value=res.message?.split(',').map((item:any)=>Number(item))
                  let selectLandsList= landMapList.value.filter((item:any)=>selectLandList.value.includes(item.properties.farmlandid))
                  let centerList =[]
                  selectLandsList.forEach((item:any)=>{
                    if(selectLandList.value.includes(item.properties.farmlandid)){
                        centerList.push({
                            lon: Number(item.properties.locationlongitude), 
                            lat: Number(item.properties.locationlatitude)
                        })
                        landMap.value.selectFarmLandChangeColor(item.properties.farmlandid,flattenArrayList(item.geometry.coordinates))
                    }
                })
                landMap.value.setMapCenter(centerList)
            }
    }
}

const setSelectPlantList =async ()=>{
      defaultSelectLandColors()
      landMap.value.setMapCenter(landMapList.value.map((item:any)=>{
             return {
              lon: Number(item.properties.locationlongitude), 
              lat: Number(item.properties.locationlatitude)
            }
    }))

   //已经估产地块列表信息
    if(getCookie('plantingPlanTaskId')){
      //taskRecordType 任务记录类型:[1->农事；2->长势；3->种药肥；4->产量]
       //productionTypeId 估产类型ID[1->经验估产；2->实收估产；3->湿谷子估产]
        let res = await getProcessedLandList({
          plantingPlanTaskId:getCookie('plantingPlanTaskId'),
          taskRecordType:getCookie('taskRecordType'),
          productionTypeId:getCookie('productionTypeId')
        })
        if(res.success){
          setCookie('plantingPlanTaskId','')
          setCookie('taskRecordType','')
          setCookie('productionTypeId','')
          guchangLandList.value = res.data||[]
            let selectLandsList= landMapList.value.filter((item:any)=>guchangLandList.value.includes(item.properties.farmlandid))
              selectLandsList=  getArraytList(selectLandsList,300)
              selectLandsList.forEach((list:any,index:any) => {
                window.setTimeout(()=>{
                    list.forEach((item:any)=>{
                        if(guchangLandList.value.includes(item.properties.farmlandid)){
                            landMap.value.selectFarmLandChangeColor(item.properties.farmlandid,flattenArrayList(item.geometry.coordinates),'#ff9c00')
                        }
                    })
                },index*500)
            })
      }
    }  
}

const getMapSize = computed(()=>{
  let totalSize=0
  let listLand= landMapList.value.filter((item:any) => {
    return selectLandList.value.includes(item.properties.farmlandid)
  })
  listLand.forEach((item:any)=>{
      totalSize+=item?.properties?.mapareasize||0
  })
  return totalSize.toFixed(2)
})


const onClickLand =(row:any)=>{
  if(queryType.value==0){
      return
    }
    //边角错误地块过滤
    let isLand = landMapList.value.find((item:any)=>item.properties.farmlandid==row?.features[0]?.properties?.farmlandid)

    if(!isLand){
      return false
    }
     //已经估产的地块不可选
     let isguchangLand = guchangLandList.value.find((item:any)=>item==row?.features[0]?.properties?.farmlandid)
    if(isguchangLand){
      return false
    }
    //处理任务地块 如果不在该方案下不可选地块
    // if(getCookie('plantingPlanTaskId')&& !selectPlantLandList.value.includes(row?.features[0]?.properties?.farmlandid)){
    //   return false
    // }
  //如果包含原地块ID 移除地块
  if(selectLandList.value.includes(row?.features[0]?.properties?.farmlandid)){
    let index = selectLandList.value.indexOf(row?.features[0]?.properties?.farmlandid)
    selectLandList.value.splice(index, 1)
    landMap.value.removeLandColor(row?.features[0]?.properties?.farmlandid)
  }else{
      let landIds =[row?.features[0]?.properties?.farmlandid]
      selectLandList.value=Array.from(new Set(selectLandList.value.concat(landIds)))
      row?.features.forEach((item)=>{
        let selectlands =[]
        item.geometry.coordinates.forEach((list)=>{
          list.forEach((m)=>{
            selectlands.push(m[0])
            selectlands.push(m[1])
          })
        })
        landMap.value.selectFarmLandChangeColor(item.properties.farmlandid,selectlands)
      })
  }
}

const btnOpen =(item:any)=>{
  showPicker.value= true
  title.value= item.text
  formdataKey.value=item.key
  popType.value = item.value
  selectedValues.value =[formdata[item.key]]||['']
  let objlist ={ meaning: '全部', code: '' }
  if(item.value==2){
    columns.value =[objlist,...landGroupList.value] 
  }else if(item.value==3){
    columns.value =[objlist,...cropList.value] 
  }else if(item.value==4){
    columns.value =[objlist,...landTypeList.value] 
  }else if(item.value==5){
    columns.value =[objlist,...tagsTypeList.value] 
  }
}
const getTextName =(Id:any,key:any)=>{
  if(key=='landGroupId'){
   return landGroupList.value.find((row:any)=>row.code==Id)?.meaning
  }
  if(key=='cropId'){
   return cropList.value.find((row:any)=>row.code==Id)?.meaning
  }
  if(key=='landTypeId'){
   return landTypeList.value.find((row:any)=>row.code==Id)?.meaning
  }
  if(key=='landTagId'){
   return tagsTypeList.value.find((row:any)=>row.code==Id)?.meaning
  }
  return ''
}

const onConfirm =(item:any)=>{
  showPicker.value= false
  formdata[formdataKey.value]=item.selectedValues[0]
  let params={
      landgroupid:formdata.landGroupId,
      landtypeid:formdata.landTypeId,
      landname:formdata?.farmLandName,
      landtagids:formdata?.landTagId
   }
  landMap.value.queryLandList(params)
  selectLandList.value=[]
  landMap.value.removeFarmLandChangeColor()
}
//定位当前
const btnLocation =()=>{
   wx.getLocation({
        type: 'wgs84',
        success: (res:any)=> {
          locationObj.value = {
            longitude:Number(res.longitude),
            latitude:Number(res.latitude)
          }
        },
        fail: (err:any)=> {
        }
   });
}
const onSearch =(row:any)=>{
  showPicker.value = false
  let location= {
      longitude:row.longitude,
      latitude:row.latitude
    }
    locationObj.value = location
}

const btnSave =()=>{
    setCookie('plantingPlanTaskId','')
   wx.miniProgram.navigateBack()
   wx.miniProgram.postMessage({data:{total:getMapSize.value,landList:selectLandList.value}})
}
</script>
<style lang="scss" scoped>
.map-view{
  height:100vh;
  width:100vw;
  position: relative;
  overflow: hidden;
}
.right-bottom-view .van-button{
  --van-button-normal-font-size:12px;
  --van-button-normal-padding:2px 4px;
  --van-button-default-height: 30px;
  --van-button-default-line-height:30px;
}
.total-view{
  display: flex;
  z-index: 999;
  position: absolute;
  top:10px;
  width:300px;
  left:50%;
  margin-left:-150px;
  align-items: center;
  justify-content: space-between;
  .item{
    color:#fff;
    font-size:13px;
    background-color: #00000090;
    border-radius:4px;
    width:120px;
    text-align: center;
    padding:5px 0;
    .num{
      font-size:15px;
      font-weight: bold;
    }
  }
}
.right-bottom-view{
  z-index: 999;
  position: absolute;
  bottom:60px;
  right: 10px;
  width:100px;
  text-align: right;
  .btn-top{
    margin-top:6px;
    width:70px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
}
.location-view{
  position: absolute;
  z-index:99;
  left:10px;
  bottom:130px;
  height:40px;
  width:40px;
  background-color: #fff;
  border-radius:4px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size:15px;
  .icon-location::before{
    font-size:24px;
  }
}

.header-view{
  display: flex;
  position: absolute;
  top:0;
  height:30px;
  width:100%;
  left:50%;
  margin-left:-50%;
  align-items: center;
  justify-content: center;
  padding:0 10px;
  color: #fff;
  font-size:12px;
  background-color: #00000050;
  z-index:999;
}
.footer-view{
  display: flex;
  position: absolute;
  bottom:0;
  height:50px;
  width:100%;
  left:50%;
  margin-left:-50%;
  align-items: center;
  justify-content: space-between;
  padding:0 10px;
  color: #fff;
  font-size:14px;
  background-color: #00000050;
  span{
    font-size:15px;
    color: #07c160;
    padding:0 2px;
  }
}
.btn-save{
  width:70px;
}
.choose-view{
  position: absolute;
  z-index:99;
  left:10px;
  bottom:80px;
  height:40px;
  width:40px;
  >div{
    text-align: center;
    font-size:12px;
    color: #fff;
    background-color: #07c160;
    margin-bottom:2px;
    border:1px solid #07c160;

  }
}

</style>
